﻿<?php
// Prevent PHP from stopping the script after 30 sec
set_time_limit(0);
//removes notices
error_reporting(E_ALL ^ E_NOTICE);
//connect to database
$link = con();

//settings
$chan[0] = "#penthero";
$chan[1] = "#gw2sverige";
$chan[2] = "#primetime";
$chan[3] = "#ondbot";
$chan[4] = "#stderr";
$chan[5] = "#jacqli";
$server = "irc.quakenet.org";
$port = 6667;
$nick = "Jacqli";
$ctimer = 4;
$enable = false;
$enablels = false;
$master = "penthero";
$mods = array();
$checknum = 0;
$xmldata = "C:\\wamp\\www\\data.xml";
$loggedin = array();
$users = array();
$trivia = false;
$triviatime = 30;
date_default_timezone_set('Europe/Stockholm');
$dltimer = 2;
$maxmsg = 30;
$currmsg = 0;
$pingtime;
$lastmsg = "";
$srepl = false;

//get mod/admins
$result = mysql_query("SELECT nick FROM users WHERE `admin`=1 OR `mod`=1");
$i = 0;
while($row = mysql_fetch_array($result)){
	$mods[$i] = $row[0];
	$i++;
}
echo "\nADMIN+MODS\n";
print_r($mods);

//checks so we dont get quakenets MOTD
$MOTD = false;
 
//setting up bot info on irc
$thread = @JobStartAsync('localhost','/Jacqli-j1.php') or die("could not connect: $errstr ($errno)"); //connect to the script that checks news on different sites
echo "Thread started.\n";
//get the latest num of used gee's

main: $socket = @fsockopen($server, $port); //connect to the irc-server
if(!$socket){
	echo "trying to reconnect...\n";
	sleep(60);
	goto main;
}
echo "connected to irc.\n";
$uptime = time();
$nick = "Jacqli";
sleep(1);
fputs($socket,"USER $nick $nick $nick $nick :$nick\n");
fputs($socket,"NICK $nick\n");
flush();
$logincount = 0;

while($logincount < 10) {
	$logincount++;
	$data = fgets($socket, 128);	
	echo nl2br($data);

	// Separate all data
	$ex = explode(' ', $data);

	// Send PONG back to the server
	if($ex[0] == "PING"){
		fputs($socket, "PONG ".$ex[1]."\n");
	}
	flush();
}
sleep(1);
fputs($socket,"PRIVMSG Q@CServe.quakenet.org : AUTH Jacqli MnPd3uFYTc");
fgets($socket);
fputs($socket,"MODE $nick +i\n");
fputs($socket,"MODE $nick +x\n");
sleep(1);

$result = mysql_query("SELECT channel FROM channels");
while($row = mysql_fetch_array($result)){
	fputs($socket,"JOIN ".$row[0]."\n");
	echo "joined channel: ".$row[0]."\n";
	usleep(500000);
}

//set initial timers
$time = time();
$pingtime = time();

//get the latest number of usrs in #penthero
$file = file_get_contents($xmldata);
preg_match('@<gw2users>[^<]+@',$file,$file);
$gw2users = str_replace("<gw2users>","",$file[0]);


//start inf-loop that checks input and timers
while(1) {	
	if($trivia && (time() - $time) > $triviatime){
		fputs($socket, "PRIVMSG ".$trivchan." :out of time.\n");
		$currnum++;
		if($currnum < $num){
			
			$numrows = mysql_num_rows(mysql_query("SELECT id FROM trivia"));
			$rand = mt_rand(1,$numrows);
			echo $rand."\n";
			$row = mysql_fetch_row(mysql_query("SELECT Question FROM trivia WHERE id=$rand"));
			$question = $row[0];
			echo $question."\n";
			fputs($socket, "PRIVMSG ".$trivchan." :".($currnum+1).". ".$question."\n");
			$row = mysql_fetch_row(mysql_query("SELECT Answer FROM trivia WHERE id=$rand"));
			$answer = mb_strtolower(trim($row[0]),'UTF-8');
			echo $answer."\n";
			$time = time();	
		}else{
			fputs($socket, "PRIVMSG ".$trivchan." :all questions finished.\n");
			$trivia = false;
		}
		flush();
	}else if(time() - $time > 200){
		mysql_close($link);
		$link = con();
	
		$r = JobPollAsync($thread);
		echo date("[H:i:s] d-m-Y").": RESPONSE:".$r."\n";
		if ($r !== false && $r != ""){
			$tmp = explode("\n",$r);
			foreach ($tmp as &$tmp){
				$tmp2 = explode(" ",$tmp);
				//echo $tmp."\n";
				if($tmp2[0] == "PRIVMSG"){
					msg($socket, $tmp."\n",0);
					flush(); @ob_flush();
					sleep(2);
				}
			}
		}else{
			fclose($thread);
			flush();
			echo "stream got closed\n";
			$thread = @JobStartAsync('localhost','/Jacqli-j1.php') or die("could not connect: $errstr ($errno)"); //connect to the script that checks news on different sites
		}
		
		$time = time();
	}else if(time() - $pingtime > 400){
		fclose($socket);
		flush();
		echo "trying to reconnect...\n";
		sleep(60);
		goto main;
	}

	stream_set_blocking($socket,false);
	if($data = fgets($socket)){
		$pingtime = time();
		stream_set_blocking($socket,true);
		echo date("[H:i:s] d-m-Y").": ".$data;
		
		flush();
		$ex = explode(' ', $data);
		$rawcmd = str_replace(chr(13), '', str_replace(chr(10), '', explode(':', $ex[3]))); //removes newlines and get the command
		//$oneword = explode('<br>', $rawcmd);
		$channel = $ex[2];
		
		$nicka = explode('@', $ex[0]);
		$nickb = explode('!', $nicka[0]);
		$nickc = explode(':', $nickb[0]);
 
		$host = $nicka[1];
		$nick = $nickc[1];
		echo $host."\n";
	    
		//we gotta respond to the PING's with a PONG
		if($ex[0] == "PING"){
			fputs($socket, "PONG ".$ex[1]."\n");
		}else{
			$args = ""; 
			for ($i = 4; $i < count($ex); $i++) { 
				$args .= $ex[$i].' '; 
			}

			//this section checks if we get a url we can check
			if(preg_match('@\s+http://([^/,\s\.]+\.)+[a-zA-Z]+(/[^\s]*)?@i'," ".$args,$url)){
				$url[0] = str_replace(" ","",$url[0]);
				$https = false;
			}elseif($rawcmd[1] == "http"){
				if(preg_match('@//([^/,\s\.]+\.)+[a-zA-Z]+(/[^\s]*)?@i',$rawcmd[2],$url)){
					$url[0] = "http:".$url[0];
					$https = false;
				}
			}elseif(preg_match('@\s+www\.([^/,\s\.]+\.)+[a-zA-Z]+(/[^\s]*)?@i'," ".$args,$url)){
				$url[0] = str_replace(" ","",$url[0]);
				$https = false;
			}elseif(preg_match('@\swww\.([^/,\s\.]+\.)+[a-zA-Z]+(/[^\s]*)?@i'," ".$rawcmd[1],$url)){
				$url[0] = str_replace(" ","",$url[0]);
				$https = false;
			}elseif(preg_match('@\s+https://([^/,\s\.]+\.)+[a-zA-Z]+(/[^\s]*)?@i'," ".$args,$url)){
				$url[0] = str_replace(" ","",$url[0]);
				$https = true;
			}elseif($rawcmd[1] == "https"){
				if(preg_match('@//([^/,\s\.]+\.)+[a-zA-Z]+(/[^\s]*)?@i',$rawcmd[2],$url)){
					$url[0] = "https:".$url[0];
					$https = true;
				}
			}
	
			//checks if we got a s/x/y/w message
			if(sizeof($args) != 0)
				$strplit = explode('/',$rawcmd[1]." $args");
			else
				$strplit = explode('/',$rawcmd[1]);
			if(sizeof($strplit) == 4 && $strplit[0] == 's'){
				$tmpstr = preg_replace('@'.$strplit[1].'@'.$strplit[3],$strplit[2],$lastmsg); 
				$currmsg = msg($socket, "PRIVMSG ".$channel." :".$tmpstr."\n",$currmsg);
				$srepl = true;
			}elseif(sizeof($strplit) == 3 && $strplit[0] == 's'){
				$tmpstr = preg_replace('@'.$strplit[1].'@',$strplit[2],$lastmsg); 
				$currmsg = msg($socket, "PRIVMSG ".$channel." :".$tmpstr."\n",$currmsg);
				$srepl = true;
			}
			
			echo "COMMAND:".$ex[1]."\n";
			//time to check what Jacqli will do
			if($ex[1] == "PRIVMSG" && $currmsg < $maxmsg){
				if(!$srepl){
					if(sizeof($args != 0))
						$lastmsg = $rawcmd[1]." ".$args;
					else
						$lastmsg = $rawcmd[1];
				}else
					$srepl = false;
					
				if($rawcmd[1] == "!echo" && !$trivia){
					echo $users[$nick]."\n";
					if($users[$nick] != $master){
						$currmsg = msg($socket, "PRIVMSG ".$channel." :".$args."\n",$currmsg);
					}else{
						$currmsg = msg($socket, $args."\n",$currmsg);
						echo "ARGS:".$args."\n";
					}
					flush();
				}elseif ($rawcmd[1] == "!help" && !$trivia && $channel[0] == "#") {
					$currmsg = msg($socket, "PRIVMSG ".$channel." : [Commands] Channel: !help, !online, !google <search>, !youtube <search>, !gw2 <search> | Private: !register <nick> <pw>, !login <nick> <pw>\n",$currmsg);
				}elseif ($rawcmd[1] == "!md5" && !$trivia && $channel[0] == "#"){
					$currmsg = msg($socket, "PRIVMSG ".$channel." :".md5($args)."\n",$currmsg);
				}elseif($rawcmd[1] == "!youtube" || $rawcmd[1] == "!yt" && !$trivia && $channel[0] == "#"){ // !YOUTUBE
					if($args == NULL){
						$currmsg = msg($socket, "PRIVMSG ".$channel." :[YouTube] Usage: !youtube <what to search for>\n",$currmsg);
					}else{
						$fp = @fsockopen("www.youtube.com", 80, $errno, $errstr, $ctimer);
						if (!$fp){
							echo "$errstr ($errno)\n";
						}else {
							//echo $args."\n";
							$args = urlencode($args);
							$out = "GET /results?search_type=&search_query=".$args." HTTP/1.1\r\n";
							$out .= "Host: www.youtube.com\r\n";
							$out .= "User-Agent: Jacqli/0.2 jacqli.mir@gmail.com\r\n";
							$out .= "Connection: Close\r\n\r\n";
							fwrite($fp, $out);
							//echo $out."\n";
							$turl = "";
							while (!feof($fp)) {
								$turl .= fread($fp, 1000);
							}
							fclose($fp);
							$turl = str_replace('dir="ltr"',"",str_replace("<b>","",str_replace("</b>","",$turl)));
							//echo $turl;
							if(preg_match('@<a href="/watch?[^"]+"\s*title="[^>]*>[^>]*>@', $turl, $matches)){
								preg_match('@"[^"]*"@', $matches[0], $umatch);
								preg_match('@>[^<]*<@', $matches[0], $tmatch);
								$tmatch[0] = html_entity_decode($tmatch[0],ENT_QUOTES,"UTF-8");
								
								$currmsg = msg($socket, "PRIVMSG ".$channel." :[YouTube] ".str_replace("<","",str_replace(">","",$tmatch[0]))." | http://www.youtube.com".str_replace("&amp;feature=fvst","",str_replace('"',"",$umatch[0]))."\n",$currmsg);
							}else{
								$currmsg = msg($socket, "PRIVMSG ".$channel." :no results found\n",$currmsg);
							}
						}
						flush();
					}
				}elseif($url[0] != "" && !$trivia && $channel[0] == "#"){
					$url = str_replace(array("http://","https://"),"",$url[0]);
					preg_match("@[^/]+@",$url,$matches);
					$host =  $matches[0];
					echo "HOST:".$host."\n";
					if(!$https){
						$fp = @fsockopen($host, 80, $errno, $errstr, $ctimer);
					}else{
						$fp = @fsockopen("ssl://".$host, 443, $errno, $errstr, $ctimer);
					}
					if (!$fp){
						echo "host ($host) $errstr ($errno)\n";
					}else{
						if(preg_match("@/[^\s]*@",$url,$matches)){
							$url = $matches[0];
						}else{
							$url = "/";
						}
						echo "URL:".$url."\n";
						$out = "GET ".$url." HTTP/1.1\r\n";
						$out .= "Host: ".$host."\r\n";
						$out .= "User-Agent: Jacqli/0.2 jacqli.mir@gmail.com\r\n";
						$out .= "Connection: Close\r\n\r\n";
						fwrite($fp, $out);
			
						$url = "";
						$time = time();
						$timee = time();
						while (!feof($fp) && $timee-$time <= $dltimer) {
							$url .= fread($fp, 1000);
							$timee = time();
						}
						fclose($fp);
						//echo $url."\n";
						preg_match("@<title>[^<]*@i",$url,$matches);
						//echo $url."\n";
						echo "URL-match: ".$matches[0]."\n";
						$matches[0] = preg_replace("@[ \t]+@"," ",$matches[0]);
						$title = html_entity_decode(substr(preg_replace("@<title>@i","",str_replace(array("\n","\r"),"",$matches[0])),0,300),ENT_QUOTES,"UTF-8");
						echo "TITLE:".$title."\n";
						if($title == "301 Moved" || $title == "301 Moved Permanently" || $title == "302 Found" || $title == "303 See Other" || $title == "302 Moved"){							
							echo "URL:".$url."\n";
							preg_match("@Location:[^\n\r]+@i", $url,$url);
							echo "URL2:".$url[0]."\n";
							$url = str_replace(array("Location:","http://"," "),"",$url[0]);
						
							preg_match("@[^/]+@",$url,$matches);
							$host =  $matches[0];
						
							echo "HOST:".$host."\n";
							$fp = @fsockopen($host, 80, $errno, $errstr, $ctimer);
							if (!$fp){
								echo "host ($host) $errstr ($errno)\n";
							}else{
								if(preg_match("@/[^\s]*@",$url,$matches)){
									$url = $matches[0];
								}else{
									$url = "/";
								}
								//echo "URL:".$url."\n";
								$out = "GET ".$url." HTTP/1.1\r\n";
								$out .= "Host: ".$host."\r\n";
								$out .= "User-Agent: Jacqli/0.2 jacqli.mir@gmail.com\r\n";
								$out .= "Connection: Close\r\n\r\n";
								fwrite($fp, $out);
		
								$url = "";
								$time = time();
								$timee = time();
								while (!feof($fp) && $timee-$time <= $dltimer) {
									$url .= fread($fp, 1000);
									$timee = time();
								}
								fclose($fp);
								preg_match("@<title>[^<]*@i",$url,$matches);
								echo "URL-match: ".$matches[0]."\n";
								$matches[0] = preg_replace("@[ \t]+@"," ",$matches[0]);
								$title = html_entity_decode(substr(preg_replace("@<title>@i","",str_replace(array("\n","\r"),"",$matches[0])),0,300),ENT_QUOTES,"UTF-8");
							}
						}
						$currmsg = msg($socket, "PRIVMSG ".$channel." :".$title."\n",$currmsg);
					}
					flush();					
				}elseif($rawcmd[1] == "!google" && !$trivia && $channel[0] == "#"){ // !GOOGLE
					$currmsg = $currmsg+5;
					if($args == NULL){
						$currmsg = msg($socket, "PRIVMSG ".$channel." :[Google] Usage: !google <what to search for>\n",$currmsg);
					}elseif(stristr($args,"jacqli")){
						$currmsg = msg($socket, "PRIVMSG ".$channel." :I already know everything about myself.\n",$currmsg);
					}elseif(stristr($args,"penthero")){
						$currmsg = msg($socket, "PRIVMSG ".$channel." :My master likes secrets.\n",$currmsg);
					}else{
						Google($args, $socket, $channel, $ctimer, 0);
					}
				}elseif($rawcmd[1] == "!gw2" && !$trivia && $channel[0] == "#"){ // !gw2
					$currmsg = $currmsg+5;
					if($args == NULL){
						$currmsg = msg($socket, "PRIVMSG ".$channel." :[GW2wiki] Main Page | http://wiki.guildwars2.com/wiki/Main_Page\n",$currmsg);
					}elseif(stristr($args,"jacqli")){
						$currmsg = msg($socket, "PRIVMSG ".$channel." :I already know everything about myself.\n",$currmsg);
					}else{
						Google("site%3Awiki.guildwars2.com ".$args, $socket, $channel, $ctimer, 1);
					}
				}elseif($rawcmd[1] == "!wiki" && !$trivia && $channel[0] == "#"){ // !wiki
					$currmsg = $currmsg+5;
					if($args == NULL){
						$currmsg = msg($socket, "PRIVMSG ".$channel." :[Wiki] Main Page | http://en.wikipedia.org/wiki/Main_Page\n",$currmsg);
					}elseif(stristr($args,"jacqli")){
						$currmsg = msg($socket, "PRIVMSG ".$channel." :I already know everything about myself.\n",$currmsg);
					}else{
						Google("site%3Aen.wikipedia.org ".$args, $socket, $channel, $ctimer, 3);
					}
				}elseif($rawcmd[1] == "!gw" && !$trivia && $channel[0] == "#"){ // !gw
					$currmsg = $currmsg+5;
					if($args == NULL){
						$currmsg = msg($socket, "PRIVMSG ".$channel." :[GWwiki] Main Page | http://wiki.guildwars2.com/wiki/Main_Page\n",$currmsg);
					}elseif(stristr($args,"jacqli")){
						$currmsg = msg($socket, "PRIVMSG ".$channel." :I already know everything about myself.\n",$currmsg);
					}else{
						Google("site%3Awiki.guildwars.com ".$args, $socket, $channel, $ctimer, 2);
					}
				}elseif(($rawcmd[1] == "!tran" || $rawcmd[1] == "!translate") && !$trivia && $channel[0] == "#"){ //!TRANSLATE					
					$fp = @fsockopen("translate.google.se", 80, $errno, $errstr, $ctimer);
					if (!$fp){
						echo "host ($host) $errstr ($errno)\n";
					}else{
						//echo "URL:".$url."\n";
						$out = "GET /#en|sv|".urlencode($args)." HTTP/1.1\r\n";
						$out .= "Host: translate.google.se\r\n";
						$out .= "User-Agent: Jacqli/0.2 jacqli.mir@gmail.com\r\n";
						$out .= "Connection: Close\r\n\r\n";
						fwrite($fp, $out);

						$url = "";
						$time = time();
						$timee = time();
						while (!feof($fp) && $timee-$time <= $dltimer) {
							$url .= fread($fp, 1000);
							$timee = time();
						}
						echo "URL:".$url."\n";
						fclose($fp);
						//$currmsg = msg($socket, "PRIVMSG ".$channel." :[Translate] ".$trans."\n",$currmsg);
					}
				}elseif($rawcmd[1] == "!robban" && !$trivia && $channel[0] == "#"){ //!ROBBAN
					$text = explode("\n",file_get_contents("robban.txt"));
					$currmsg = msg($socket, "PRIVMSG ".$channel." :[Robban] ".$text[mt_rand(0,sizeof($text)-1)]."\n",$currmsg);
				}elseif($rawcmd[1] == "!enable" && $users[$nick] == $master){ //!ENABLE
					$enable = !$enable;
				}elseif($rawcmd[1] == "!enablels" && $users[$nick] == $master){ //!ENABLELS
					$enablels = !$enablels;
				}elseif($rawcmd[1] == "ls" && $channel[0] == "#"){ //LS
					$currmsg = msg($socket, "NAMES ".$channel."\n",$currmsg);
				}elseif($rawcmd[1] == "!senaste" || $rawcmd[1] == "!senast" || $rawcmd[1] == "!latest" || $rawcmd[1] == "!last" && $channel[0] == "#"){ //!LAST
					$row = mysql_fetch_row(mysql_query("SELECT last FROM latest LIMIT 1"));
					$row = mysql_real_escape_string($row[0]);
					$currmsg = msg($socket,substr($row,0,500)."\n",$currmsg);
				}elseif($rawcmd[1] == "!register" && $channel[0] != "#"){ //!REGISTER
					$list = explode(" ",$args);
					if(sizeof($list) > 1 && !in_array($nick,$loggedin)){
						$user = mysql_real_escape_string(trim($list[0]));
						$pw = trim($list[1]);
						if($user == "" || $pw == ""){
							$currmsg = msg($socket, "PRIVMSG ".$nick." :register failed.\n",$currmsg);
						//echo $user." ".$pw."\n";
						}else{
							$pw = mysql_real_escape_string(md5($pw));
							
							if(mysql_query("INSERT INTO users VALUES ('$user', '$pw', '0')")) {
								$currmsg = msg($socket, "PRIVMSG ".$nick." :register complete.\n",$currmsg);
							}else{
								$currmsg = msg($socket, "PRIVMSG ".$nick." :register failed.\n",$currmsg);
							}
						}
					}else{
						$currmsg = msg($socket, "PRIVMSG ".$nick." :register failed.\n",$currmsg);
					}
				}elseif($rawcmd[1] == "!login" && $channel[0] != "#"){ //!LOGIN
					$list = explode(" ",$args);
					if(sizeof($list) > 1){						
						$user = mysql_real_escape_string($list[0]);
						$pw = mysql_real_escape_string(md5($list[1]));
						//echo $user." ".$pw."\n";
						
						$row = mysql_fetch_row(mysql_query("SELECT pw FROM users WHERE nick='$user'"));
						//echo $row[0]."\n";
						if($row[0] == $pw && !in_array($nick,$loggedin)){
							$loggedin[$nick] = $nick;
							$users[$nick] = $user;
							$currmsg = msg($socket, "PRIVMSG ".$nick." :login succeded.\n",$currmsg);
							print_r($users);
							print_r($loggedin);
						}else{
							$currmsg = msg($socket, "PRIVMSG ".$nick." :login failed.\n",$currmsg);
						}
					}else{
						$currmsg = msg($socket, "PRIVMSG ".$nick." :login failed.\n",$currmsg);
					}
				}elseif($rawcmd[1] == "!join" && $channel[0] != "#" && $users[$nick] == $master){ //!JOIN
					fputs($socket, "JOIN $args\n");
					mysql_query("INSERT INTO channels VALUES ('$args')");					
				}elseif($rawcmd[1] == "!part" && $channel[0] != "#" && $users[$nick] == $master){ //!PART
					fputs($socket, "PART $args\n");
					mysql_query("DELETE FROM channels WHERE channel='$args'");
				}elseif($rawcmd[1] == "!stop" && $trivia && $users[$nick] == in_array($nick,$mods)){ //!STOP
					$currmsg = msg($socket, "PRIVMSG ".$channel." :[Trivia] Halted.\n",$currmsg);
					$trivia = false;
				}elseif($rawcmd[1] == "!citat" && !$trivia && $channel[0] == "#"){
					if(trim($args) != "" && in_array($nick,$loggedin)){
						echo $args."\n";
						$args = html_entity_decode($args,ENT_QUOTES,"UTF-8");
						$numrows = mysql_num_rows(mysql_query("SELECT id FROM citat"))+1;
						if(mysql_query("INSERT INTO citat VALUES ('$numrows', '$args')"))
							$currmsg = msg($socket, "PRIVMSG ".$channel." :[Citat] Successfully added a quote\n",$currmsg);						
					}else{
						$numrows = mysql_num_rows(mysql_query("SELECT id FROM citat"));
						$rand = mt_rand(1,$numrows);
						echo $rand."\n";
						$row = mysql_fetch_row(mysql_query("SELECT Quote FROM citat WHERE Id=$rand"));
						$quote = $row[0];
						echo $quote."\n";
						$currmsg = msg($socket, "PRIVMSG ".$channel." :[Citat] ".$quote."\n", $currmsg);
					}
				}elseif($rawcmd[1] == "!trivia" && !$trivia && in_array($nick,$loggedin) && $channel[0] == "#"){	//!TRIVIA
					$trivchan = $channel;
					$trivia = true;
					$args = trim($args);
					if($args != "" && is_numeric($args)){
						if($args > 60){
							$num = 60;
						}else{
							$num = $args;
						}
						echo $args." isnum\n";
					}else{
						echo $args." isnotnum\n";
						$num = 5;
					}
					$currnum = 0;
					
					$numrows = mysql_num_rows(mysql_query("SELECT id FROM trivia"));
					$rand = mt_rand(1,$numrows);
					echo $rand."\n";
					$row = mysql_fetch_row(mysql_query("SELECT Question FROM trivia WHERE id=$rand"));
					$question = $row[0];
					echo $question."\n";
					$row = mysql_fetch_row(mysql_query("SELECT Answer FROM trivia WHERE id=$rand"));
					$answer = mb_strtolower(trim($row[0]),'UTF-8');
					echo $answer."\n";
					$currmsg = msg($socket, "PRIVMSG ".$channel." :".($currnum+1).". ".$question."\n",$currmsg);
					$time = time();					
				}elseif($rawcmd[1] == "!stats" && !$trivia && in_array($nick,$loggedin) && $channel[0] == "#"){	 //!STATS				
					$row = mysql_fetch_row(mysql_query("SELECT score FROM users WHERE nick='$nick' LIMIT 1"));
					$score = $row[0];
					$currmsg = msg($socket, "PRIVMSG ".$channel." :[Trivia] ".$users[$nick].": ".$score."\n",$currmsg);					
				}elseif($rawcmd[1] == "\001VERSION\001"){ //CTCP VERSION
					echo "VERSION\n";
					$currmsg = msg($socket, "NOTICE ".$nick." :\001VERSION Jacqli v0.23\001\n",$currmsg);	
				/*}elseif($rawcmd[1] == "\001PING"){ //CTCP PING
					echo "PING\n";
					$currmsg = msg($socket, "NOTICE ".$nick." :\001PING ".$args."\001\n");				
					echo "T\n";
				}elseif($rawcmd[1] == "\001TIME\001"){ //CTCP TIME
					$currmsg = msg($socket, "NOTICE ".$nick." :\001TIME :".date("[H:i:s] d-m-Y")."\001\n");				
				*/}elseif($rawcmd[1] == "!reset" && !$trivia && $users[$nick] == $master){					
					mysql_query("UPDATE users SET score=0");				
				}elseif($rawcmd[1] == "!rest" && !$trivia && $users[$nick] == $master){					
					mysql_query("UPDATE users SET score=0");				
				}elseif($rawcmd[1] == "!online" && !$trivia && $channel[0] == "#" && false){ //DISABLED					
					$fp = @fsockopen("gw2s.dyndns.info", 64738, $errno, $errstr, $ctimer); // open connection to gw2sverige's mumble
					if (!$fp){
						 $txt = "Mumble is 4offline20,";
					}else{
						$txt = "Mumble is 3online20,";
						fclose($fp);
					}
					$fp = @fsockopen("www.gw2sverige.se", 80, $errno, $errstr, $ctimer); // open connection to gw2sverige's mumble
					if (!$fp){
						 $txt .= " GW2Sverige is 4offline20\n";
					}else{
						$txt .= " GW2Sverige is 3online20\n";
						fclose($fp);
					}
					$currmsg = msg($socket, "PRIVMSG ".$channel." :[Online] ".$txt,$currmsg);									
				}elseif($rawcmd[1] == "!mods" && !$trivia && $channel[0] == "#"){	
					$modlist = "Penthero";
					for($i = 1; $i < sizeof($mods); $i++){
						$modlist = $modlist.", ".$mods[$i];
					}
					$currmsg = msg($socket, "PRIVMSG ".$channel." : My mods are: ".$modlist."\n",$currmsg);									
				}elseif($rawcmd[1] == "!top" && !$trivia && $channel[0] == "#"){
					$results = mysql_query("SELECT nick, score FROM users GROUP BY nick ORDER BY score DESC LIMIT 3");
					$i = 0;
					$result = array();
					$scores = array();
					while($row = mysql_fetch_array($results)){
						print_r($row);
						$result[$i] = $row[0];
						$scores[$i] = $row[1];
						$i++;
					} 
					$currmsg = msg($socket, "PRIVMSG ".$channel." : [Trivia] 1. ".$result[0].": ".$scores[0]." | 2. ".$result[1].": ".$scores[1]." | 3. ".$result[2].": ".$scores[2]."\n",$currmsg);					
				}elseif($trivia && mb_strtolower(trim($rawcmd[1]." ".$args),'UTF-8') == $answer && in_array($nick,$loggedin) && $channel == $trivchan){					
					$currmsg = msg($socket, "PRIVMSG ".$channel." :".$nick." got the correct answer.\n",$currmsg);
					$nick = mysql_real_escape_string($users[$nick]);
					echo "nick: ".$nick."\n";
					$row = mysql_fetch_row(mysql_query("SELECT score FROM users WHERE nick='$nick' LIMIT 1"));
					$score = $row[0]+1;
					mysql_query("UPDATE users SET score='$score' WHERE nick='$nick'");
					$currnum++;
					if($currnum < $num){
						$numrows = mysql_num_rows(mysql_query("SELECT id FROM trivia"));
						$rand = mt_rand(1,$numrows);
						echo $rand."\n";
						$row = mysql_fetch_row(mysql_query("SELECT Question FROM trivia WHERE id=$rand"));
						$question = $row[0];
						echo $question."\n";
						$row = mysql_fetch_row(mysql_query("SELECT Answer FROM trivia WHERE id=$rand"));
						$answer = mb_strtolower(trim($row[0]),'UTF-8');
						echo $answer."\n";
						msg($socket, "PRIVMSG ".$trivchan." :".($currnum+1).". ".$question."\n",$currmsg);
						$time = time();	
					}else{
						msg($socket, "PRIVMSG ".$trivchan." :all questions finished.\n",$currmsg);
						$trivia = false;
					}
					flush();
				}elseif($rawcmd[1] == "!uptime" && !$trivia && $channel[0] == "#"){
					$endtime = time() - $uptime;
					$updiff = "";
					$first = false;
					$years = (date("Y",$endtime)-1970);
					if($years != 0){
						$updiff .= "$years years ";
						$first = true;
					}
					$months = (date("n",$endtime)-1);
					if($months != 0)
						$updiff .= "$months months ";
					$days = (date("j",$endtime)-1);
					if($days != 0)
						$updiff .= "$days days ";
					$hours = (date("G",$endtime)-1);
					if($hours != 0)
						$updiff .= "$hours hours ";
					$mins = date("i",$endtime);
					if($mins != 0)
						$updiff .= "$mins minutes ";
					$secs = date("s",$endtime);
					if($secs != 0)
						$updiff .= "$secs seconds ";
   
					$currmsg = msg($socket, "PRIVMSG ".$channel." :[Uptime] I have been connected for ".$updiff."\n",$currmsg);					
				}elseif($rawcmd[1] == "!release" && !$trivia && $channel[0] == "#"){  
					$currmsg = msg($socket, "PRIVMSG ".$channel." :[Release] http://dragonwatch.net/releasedate/\n",$currmsg);
				}				
			}elseif(($ex[1] == "353") && $enablels){ //checks if we get a NAMES response from the server(is used together with "ls" command
				$args = str_replace(array("@","+","%",":"),"",$args);
				$args = explode(" ",$args);
				$channel = $args[0];
				echo "CHAN:".$channel."\n";
				unset($args[0]);
				$args = array_values($args);
				$args = implode(" ",$args);
				msg($socket, "PRIVMSG ".$channel." : ".$args."\n",$currmsg);
				$MOTD = true;
			}elseif($ex[1] == "366"){ //END MOTD
				$MOTD = false;
			}elseif($ex[1] == "JOIN" && $chan == "#gw2sverige"){ //checks if we a JOIN message 
				msg($socket, "LIST ".$channel."\n",$currmsg);
			}elseif($ex[1] == "QUIT"){ //checks if we a QUIT message
				if(in_array($nick, $loggedin)){
					unset($loggedin[$nick]);
					unset($users[$nick]);
					$loggedin = array_values($loggedin);
					$users = array_values($users);					
				}
			}elseif($ex[1] == "PART"){ //checks if we a PART message
				if(in_array($nick, $loggedin)){
					unset($loggedin[$nick]);
					unset($users[$nick]);
					$loggedin = array_values($loggedin);
					$users = array_values($users);					
				}
			}elseif($ex[1] == "NICK"){ //checks if we get NICK message
				if(in_array($nick, $loggedin)){
					$loggedin[$rawcmd[1]] = $loggedin[$nick];
					$users[$rawcmd[1]] = $users[$nick];
					
					unset($loggedin[$nick]);
					unset($users[$nick]);
					$loggedin = array_values($loggedin);
					$users = array_values($users);					
				}
			}elseif($ex[1] == "322" && $ex[3] == "#gw2sverige"){ //checks if we get a LIST response
				$args = explode(" ",$args);
				if($args[0] > $gw2users){
					$file_contents = file_get_contents($xmldata);
					$fh = fopen($xmldata, "w");
					$file_contents = str_replace("<gw2users>".$gw2users."</gw2users>","<gw2users>".$args[0]."</gw2users>",$file_contents);
					fwrite($fh, $file_contents);
					fclose($fh);
					$currmsg = msg($socket, "PRIVMSG #gw2sverige : [#GW2sverige] nytt max på: ".$args[0]." användare\n",$currmsg);
					$gw2users = $args[0];
				}
			}elseif($ex[1] == "372" || $ex[1] == "005"){ //MOTD
				$MOTD = true;
			}
		}		
	}
	if(!$MOTD){
		usleep(500000);
		if($currmsg > 0){
			$currmsg--;
		}
	}
}

function JobStartAsync($server, $url, $port=80,$conn_timeout=10, $rw_timeout=86400){
	$errno = '';
	$errstr = '';

	
	$fp = @fsockopen($server, $port, $errno, $errstr, $conn_timeout);
	if (!$fp) {
	   echo "$errstr ($errno)<br />\n";
	   return false;
	}
	$out = "GET $url HTTP/1.1\r\n";
	$out .= "Host: $server\r\n";
	$out .= "Connection: Close\r\n\r\n";
	
	stream_set_blocking($fp, false);
	stream_set_timeout($fp, $rw_timeout);
	fwrite($fp, $out);
	
	return $fp;
}

// returns false if HTTP disconnect (EOF), or a string (could be empty string) if still connected
function JobPollAsync(&$fp){
	if ($fp === false) return false;
	
	if (feof($fp)) {
		fclose($fp);
		$fp = false;
		return false;
	}
	
	return fread($fp,10000);
}

function Google($args, &$sock, $channel, $ctimer, $type){
	$fp = @fsockopen("www.google.com", 80, $errno, $errstr, $ctimer);
	if (!$fp){
		echo "$errstr ($errno)\n";
	}else {
		$args = str_replace(' ','+',str_replace(chr(13), '', str_replace(chr(10), '', $args)));
		//echo $args."\n";
		$out = "GET /search?q=".$args." HTTP/1.1\r\n";
		$out .= "Host: www.google.com\r\n";
		$out .= "User-Agent: Jacqli/0.2 jacqli.mir@gmail.com\r\n";
		$out .= "Connection: Close\r\n\r\n";
		fwrite($fp, $out);
		$results = "";
		while (!feof($fp)) {
			$results .= fread($fp, 1000);
		}
		fclose($fp);

		$results = str_replace(array('<em>','</em>','<b>','</b>'),'',$results);
		if(preg_match('@<h3 class="r"><a href="[^"]*"[^<]*@i',$results,$matches)){ //TODO: fix all these regexes so we get title & text
			if(preg_match('@<h3 class="r"><a href="[^"]*"@i',$matches[0],$url)){
				if(preg_match('@\)">[^<]*@i',$matches[0],$title)){
					$url = str_replace(array('<h3 class="r"><a href=','class=l','"'),'',html_entity_decode($url[0],ENT_QUOTES,"UTF-8"));
					$title = str_replace(array(chr(41),'"','>','class=l'),'',html_entity_decode($title[0],ENT_QUOTES,"UTF-8"));					
					fputs($sock, "PRIVMSG ".$channel." :[Google] ".$title." | ".$url."\n");
				}else{
					echo "no title found\n"; 
					fputs($sock, "PRIVMSG ".$channel." :[Google] No match found.\n");
				}
			}else{
				echo "no url found\n"; 
				fputs($sock, "PRIVMSG ".$channel." :[Google] No match found.\n");
			}
		}else{
			echo "no match at all\n"; 
			fputs($sock, "PRIVMSG ".$channel." :[Google] No match found.\n");
		}
			//echo $results;
	}
	flush();
}

function con(){
	$link = mysql_pconnect('localhost', 'Jacqli', 'hbQCSamh592Y9zYt');
	if(!$link)
	die('could not connect: ' . mysql_error());

	$db = mysql_select_db('jacqli', $link);
	if(!db)
	die('Cant\'t use Jacqli: ' . mysql_error());
	return $link;
}

function msg(&$sock, $arg, $currmsg){
	fputs($sock, $arg);
	return ($currmsg+5);
}

?>